local cjson = require("cjson")

local ngx_req = ngx.req
local ngx_log = ngx.log
local ngx_print = ngx.print
local ngx_exit = ngx.exit

local function _verify_request_params(params)
  if params.method ~= "GET" then
    return nil, "get access token not support " .. params.method .. " method"
  end
  if not params.key then
    return nil, "missing key"
  end
  return true
end

local args = ngx_req.get_uri_args()

local params = {
  method = ngx_req.get_method(),
  key = args.key,
}

local ok, err = _verify_request_params(params)

if not ok then
  ngx_log(ngx.ERR, "failed to verify server: ", err)
  ngx_print(cjson.encode({ errmsg = "failed to verify request: " .. err }))
  return ngx_exit(ngx.HTTP_OK)
end

ngx.header["Content-Type"] = "application/json;charset=UTF-8"

local red = require("resty.wechat.utils.redis"):connect(wechat_config.redis).redis

local key_exist = red:sismember("app_set", params.key)

if key_exist and key_exist == 0 then
  ngx_print(cjson.encode({ errmsg = "app_key:[" .. params.key .. "] is not registered!" }))
  return ngx_exit(ngx.HTTP_OK)
end

local access_token_key = "access_token:" .. params.key
local access_token = red:get(access_token_key)

if access_token == null then
  ngx_print(cjson.encode({ errmsg = "access_token_key:[" .. access_token_key .. "] not found in redis !" }))
  return ngx_exit(ngx.HTTP_OK)
end

local access_token_expire_time = red:ttl(access_token_key)

ngx_print(cjson.encode({ access_token = access_token, expires_in = access_token_expire_time }))

return ngx_exit(ngx.HTTP_OK)
